﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using compshop.web.CompShopDataService;
using System.Drawing;

namespace compshop.web
{
    /// <summary>
    /// 
    /// </summary>
    public partial class _Default : System.Web.UI.Page
    {
        public const string AddToBasketCommandName = "AddToBasket";
        public const string ShowParametersCommandName = "ShowParameters";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                PopulateMenu();
            }
            

            int id;
            if (int.TryParse(Request.Params["idParam"], out id))
            {
                GeneralProduct gp = ObjectDataSource.GetGeneralProductById(id);

            }
                
            UpdateBasket();
        }

        protected void PopulateMenu()
        {
            tvCategories.Nodes.Clear();
            var categories = (from c in ObjectDataSource.csEntities.Categories.Expand("SubCategories")
                              orderby c.Name
                              select c).ToList();
            foreach (Category c in categories)
            {
                TreeNode treeNode = new TreeNode(c.Name, c.CategoryID.ToString());
                foreach (SubCategory s in c.SubCategories)
                {
                    treeNode.ChildNodes.Add(new TreeNode(s.Name, s.SubCategoryID.ToString()));
                }
                if (treeNode.ChildNodes.Count > 0)
                {
                    tvCategories.Nodes.Add(treeNode);
                }
            }
            tvCategories.CollapseAll();
        }

        protected void tvCategories_SelectedNodeChanged(object sender, EventArgs e)
        {
            if (tvCategories.SelectedNode == null)
            {
                odsProducts.SelectParameters["subCategory"].DefaultValue = (-1).ToString();
                odsProducts.SelectParameters["subCategory"].DefaultValue = (-1).ToString();
                return;
            }
            if (tvCategories.SelectedNode.ChildNodes.Count == 0)
            {
                //                            <asp:Parameter DefaultValue="-1" Name="category" Type="Int32" />
                //                            <asp:Parameter DefaultValue="-1" Name="subCategory" Type="Int32" />
                //                           <asp:Parameter DefaultValue="-1" Name="producer" Type="Int32" />
                odsProducts.SelectParameters["subCategory"].DefaultValue = tvCategories.SelectedNode.Value;
            }
            else
            {
                odsProducts.SelectParameters["category"].DefaultValue = tvCategories.SelectedNode.Value;
                odsProducts.SelectParameters["subCategory"].DefaultValue = (-1).ToString();
            }
            odsProducts.DataBind();
        }

        protected void lvProducts_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case AddToBasketCommandName:
                    {
                        int id;
                        if (int.TryParse(e.CommandArgument.ToString(), out id))
                        {
                            ProductList prdList = GetProductList();
                            bool isExist = false;

                            foreach (SimpleProduct sp in prdList)
                            {
                                if (sp.ProductID == id && sp.Count == 5)
                                {
                                    pFull.InnerText = "Заказ более пяти единиц товара данной категории невозможен.";
                                    pFull.Visible = true;
                                    return;
                                }

                                if (sp.ProductID == id)
                                    isExist = true;
                            }

                            if (prdList.Count >= 5 && !isExist)
                            {
                                pFull.InnerText = "Заказ более пяти видов товаров невозможен.";
                                pFull.Visible = true;
                                return;
                            }

                            prdList.Add(id);
                            UpdateBasket();
                        }
                    }
                    break;

                case ShowParametersCommandName:
                    {
                        int id;
                        if (int.TryParse(e.CommandArgument.ToString(), out id))
                        {
                            List<GeneralProductParameter> parameters = ObjectDataSource.GetParameters(id);
                            if (parameters != null)
                            {
                                Label lblParam;
                                int counter = 0;
                                foreach (GeneralProductParameter param in parameters)
                                {
                                    lblParam = new Label();
                                    //lblParam.Width
                                    lblParam.Text = string.Format("{0} : {1} {2}", param.Parameter.Name, param.Value.ToString(), param.Parameter.Unit);
                                    lblParam.BackColor = counter % 2 != 0 ? Color.LightBlue : Color.Lavender;
                                   
                                    counter++;
                                }
                                Session["idParam"] = id;
                                Response.Redirect("ParametersForm.aspx");
                            }
                        }
                    }
                    break;
            }
        }

        #region Лишние методы
        protected void AddToBasket(int GeneralProductID)
        {
            ProductList pl = GetProductList();
            pl.Add(GeneralProductID);
        }

        protected string GetPrice()
        {
            ProductList pl = GetProductList();
            return pl.GetSum().ToString("F2");
        }

        protected string GetProductCount()
        {
            ProductList pl = GetProductList();
            return pl.GetProductCount().ToString();
        }
        #endregion

        private ProductList GetProductList()
        {
            object basket = Session["Basket"];
            if (basket == null)
            {
                basket = new ProductList();
                Session["Basket"] = basket;
            }
            if (!(basket is ProductList))
            {
                // reise error here
                return new ProductList();
            }
            return basket as ProductList;
        }

        private void UpdateBasket()
        {
            ProductList pl = GetProductList();
            int countProduct = pl.GetProductCount();

            lblProductsCount.Text = countProduct.ToString();
            lblSum.Text = pl.GetSum().ToString("F2");

            if (pl != null)
            {
                if (pl.Count > 0 && pl.Count < 5)
                    btnBasket.ImageUrl = "~/images/car.png";
                else
                    if (pl.Count == 5)
                        btnBasket.ImageUrl = "~/images/carfull.jpg";
                    else
                        btnBasket.ImageUrl = "~/images/carempty.png";
            }

            pFull.InnerText = string.Empty;
            pFull.Visible = false;
        }

        protected void btnBasket_Click(object sender, ImageClickEventArgs e)
        {
            ProductList prdList = Session["Basket"] as ProductList;
            if (prdList != null && prdList.Count > 0)
            {
                Response.Redirect("EditOrderForm.aspx");
            }
        }

        protected void btnClearBasket_Click(object sender, EventArgs e)
        {
            Session["Basket"] = new ProductList();
            UpdateBasket();
        }

        protected void btnConfirmOrder_Click(object sender, EventArgs e)
        {
            ProductList prdList = Session["Basket"] as ProductList;
            if (prdList != null && prdList.Count > 0)
            {
                Response.Redirect("EditOrderForm.aspx");
            }
        }
    }
}
